﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
    public class LapBaoCaoTonThangBLL : BaseBLL
    {
        public class SachOnGui
        {
            int _ID;
            int _TonDau;
            int _PhatSinh;

            public int ID
            {
                get { return _ID; }
                set { _ID = value; }
            }
            
            public int TonDau
            {
                get { return _TonDau; }
                set { _TonDau = value; }
            }
            
            public int PhatSinh
            {
                get { return _PhatSinh; }
                set { _PhatSinh = value; }
            }

            public SachOnGui()
            {
                _ID = -1;
                _TonDau = 0;
                _PhatSinh = 0;
            }
        }

        DAL.DauSachDAO _DauSachDAO;
        DAL.BaoCaoTonThangDAO _BaoCaoTonDAO;

        public LapBaoCaoTonThangBLL()
        {
            _DauSachDAO = new DAL.DauSachDAO();
            _BaoCaoTonDAO = new DAL.BaoCaoTonThangDAO();
        }

        public int LapBaoCao(int Thang, List<SachOnGui> sachs)
        {
            try
            {
                System.Data.SqlClient.SqlConnection Connection = OpenConnection();
                System.Data.SqlClient.SqlTransaction Transaction = BeginTransaction();

                DTO.BaoCaoTonThangDTO baocaoDto = new DTO.BaoCaoTonThangDTO();
                baocaoDto.Thang = Thang;

                foreach (SachOnGui s in sachs)
                {
                    DTO.DauSachDTO sachDto = new DTO.DauSachDTO();
                    sachDto.ID = s.ID;
                    if (_DauSachDAO.Select(Connection,Transaction, ref sachDto) <= 0)
                    {
                        Rollback();
                        CloseConnection();
                        return 1;
                    }

                    baocaoDto.IDSach = s.ID;
                    baocaoDto.TonDau = s.TonDau;
                    baocaoDto.PhatSinh = s.PhatSinh;
                    baocaoDto.TonCuoi = s.TonDau + s.PhatSinh;

                    _BaoCaoTonDAO.Insert(Connection, Transaction, baocaoDto);
                }

                Commit();
                CloseConnection();
                return 0;
            }
            catch (System.Exception ex)
            {
                Rollback();
                CloseConnection();
                throw new System.Exception("LapBaoCao Failed " + ex.Message);
            }
            finally
            {
                CloseConnection();
            }
        }
    }
}
